//
//  LoginViewController.m
//  WeiMo
//
//  Created by weixian he on 12-9-5.
//  Copyright (c) 2012年 . All rights reserved.
//

#import "LoginViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "UIGlossyButton.h"
#import "UIView+LayerEffects.h"
#import "RegViewController.h"
#import "FMManager.h"
#import "InterfaceDefine.h"
#import "JSONKit.h"
#import "SFHFKeychainUtils.h"

@interface LoginViewController ()
{
    UITextField *mCurTextField;
    MBProgressHUD *mHUD;
}
@property(nonatomic,retain) UIView *headerView;
@property(nonatomic,retain) UIView *footerView2;
@property(nonatomic,copy) NSString *name;
@property(nonatomic,copy) NSString *pwd;
@property(nonatomic,retain) UITextField *pwdTextField;
@property(nonatomic,retain) UITextField *nameTextField;
@end

@implementation LoginViewController
@synthesize delegate;
@synthesize headerView,footerView2;
@synthesize name,pwd;
@synthesize pwdTextField,nameTextField;

-(void)dealloc
{
    self.delegate = nil;
    self.name = nil;
    self.pwd = nil;
    self.footerView2 = nil;
    self.headerView = nil;
    self.pwdTextField = nil;
    self.nameTextField = nil;
    [super dealloc];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.title = NSLocalizedString(@"登录", @"login");
        self.tabBarItem.image = [UIImage imageNamed:@"ku"];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[UIBarButtonItem appearance] setTintColor:[UIColor blackColor]];
    
    UIBarButtonItem *backBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain  target:self action:@selector(backBtnClick:)];
    self.navigationItem.leftBarButtonItem = backBtnItem;
    [backBtnItem release];
    
    NSString *userName = [SFHFKeychainUtils getPasswordForUsername:kUserName andServiceName:kAppName error:nil];
    if(userName)
    {
        self.name = userName;
    }
    
    UIImage *image = [UIImage imageNamed:@"bg.png"];
    [self.view setBackgroundColor:[UIColor colorWithPatternImage: image]];
    
    UIImageView *logolView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo.png"]] autorelease];
    int w = 234;
    int h = 80;
    int x = (self.view.frame.size.width - w )/2;
    int y = 30;
    logolView.frame = CGRectMake(x, y, w, h);
    self.headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 120)] autorelease];
    self.headerView.backgroundColor = [UIColor clearColor];
    [self.headerView addSubview:logolView];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if(section == 0)
    {
        return 2;
    }
    else {
        return 1;
    }
    
}

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        return 46;
    }
    else {
        return 44.0;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        int row = indexPath.row;
        static NSString *logCellIdentifier = @"logCellIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:logCellIdentifier];
        if(cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:logCellIdentifier] autorelease];
        }
        CGRect rect = CGRectMake(0, 14, 190, 28);
        if(row == 0)
        {
            if(self.nameTextField == nil)
            {
                self.nameTextField = [[[UITextField alloc] initWithFrame:rect] autorelease];
                self.nameTextField.delegate = self;
                //textField.layer.borderWidth = 0.5;
                self.nameTextField.tag = 100;
                if(self.name)
                {
                    self.nameTextField.text = self.name;
                }
                //[textField setBorderStyle:UITextBorderStyleRoundedRect]; //外框类型
                self.nameTextField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
            }
           
            cell.textLabel.text = @"登录账号:";
            cell.accessoryView = self.nameTextField;
            cell.textLabel.textColor = [UIColor grayColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        else if( row == 1)
        {
            if(self.pwdTextField == nil)
            {
                self.pwdTextField = [[[UITextField alloc] initWithFrame:rect] autorelease];
                self.pwdTextField.delegate = self;
                //[textField setBorderStyle:UITextBorderStyleRoundedRect]; //外框类型
                
                //textField.placeholder = @"password"; //默认显示的字
                
                self.pwdTextField.secureTextEntry = YES; //密码
                
                self.pwdTextField.autocorrectionType = UITextAutocorrectionTypeNo;
                self.pwdTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
                self.pwdTextField.returnKeyType = UIReturnKeyDone;
                
                self.pwdTextField.tag = 101;
            }
           
            cell.textLabel.text = @"登录密码:";
            cell.accessoryView = self.pwdTextField;
            cell.textLabel.textColor = [UIColor grayColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        return cell;
    }
    else {
        static NSString *logCellIdentifier2 = @"logCellIdentifier2";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:logCellIdentifier2];
        if(cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:logCellIdentifier2] autorelease];
        }
        
        cell.textLabel.text = @"登录";
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.textLabel.textColor = [UIColor grayColor];
        return cell;
    }
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if(section == 1)
    {
        if(self.footerView2 == nil)
        {
            int footerW = 300;
            //int footerH = 120;
            int footerH = 80;
            self.footerView2 = [[[UIView alloc] initWithFrame:CGRectMake(10, 0, footerW, footerH)] autorelease];
            self.footerView2.backgroundColor = [UIColor clearColor];
            float w = 100;
            float h = 44;
            UIGlossyButton *registBtn = [[UIGlossyButton alloc] initWithFrame: CGRectMake((footerW - w)/2 + 10, footerH - h, w, h)];
            [registBtn addTarget:self action:@selector(registBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            registBtn.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
            registBtn.titleLabel.textAlignment = UITextAlignmentCenter;
            [registBtn setTitle:@"注册" forState:UIControlStateNormal];
            //[registBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
           	[registBtn useWhiteLabel: YES];
            registBtn.buttonCornerRadius = 3.0; registBtn.buttonBorderWidth = 1.0f;
            [registBtn setStrokeType: kUIGlossyButtonStrokeTypeBevelUp];
            registBtn.tintColor = registBtn.borderColor = [UIColor colorWithRed:100/255.0f green:100/255.0f blue:100/255.0f alpha:1.0f];
            [self.footerView2 addSubview:registBtn];
            [registBtn release];
        }
        return self.footerView2;
    }
    
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(section == 0)
    {
        return self.headerView;
    }
    return nil;
}

-(float)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0)
    {
        return self.headerView.frame.size.height;
    }
    else {
        return 0;
    }
}
-(float)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if(section == 0)
    {
        return 5;
    }
    else {
        return 120;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1)
    {
        [self saveCurTextField:mCurTextField];
        if(mCurTextField)
        {
            [mCurTextField resignFirstResponder];
        }
        //NSLog(@"name = %@, pwd = %@",self.name,self.pwd);
        [self coLogin];
    }
}

#pragma mark - UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if(textField.tag == 100)
    {
        [self.pwdTextField becomeFirstResponder];
    }
    else if(textField.tag == 101)
    {
        [textField resignFirstResponder];
        //NSLog(@"name = %@, pwd = %@",self.name,self.pwd);
        [self coLogin];
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField;
{
    mCurTextField  = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self saveCurTextField:textField];
}


#pragma mark -private
- (void)saveCurTextField:(UITextField *)textField
{
    if(textField)
    {
        if(textField.tag == 100)
        {
            self.name = textField.text;
        }
        else if(textField.tag == 101)
        {
            self.pwd = textField.text;
        }
    }
}

- (void)backBtnClick:(id)sender
{
    [self dismissModalViewControllerAnimated:YES];
}

- (void)registBtnClick:(id)sender
{
    RegViewController *regCtrl = [[[RegViewController alloc] init] autorelease];
    [regCtrl initWithStyle:UITableViewStyleGrouped];
    regCtrl.delegate = self;
    regCtrl.title = @"注册";
    [self.navigationController pushViewController:regCtrl animated:YES];
}

-(void)showAlertView:(NSString *)message
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil,nil];
    [alertView show];
    [alertView release];
}
- (void)coLogin
{
    if(self.name == nil || [self.name isEqualToString:@""])
    {
        [self showAlertView:@"登录用户不能为空!"];
        return;
    }
    else if(self.pwd == nil || [self.pwd isEqualToString:@""])
    {
        [self showAlertView:@"登录密码不能为空!"];
        return;
    }
    
    mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    [self.navigationController.view addSubview:mHUD];
    mHUD.delegate = self;
    [mHUD show:YES];
    
    NSString *urlStr =[NSString stringWithFormat:@"%@/%@",kHttpHost,kUserLogin];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:self.name forKey:@"userAccountid"];
    [dic setObject:self.pwd forKey:@"userPassword"];
    NSString *postStr = [dic JSONString];
    [dic release];
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlStr]];
    [request appendPostData:[postStr dataUsingEncoding:NSUTF8StringEncoding]];
    [request setRequestMethod:@"POST"];
    request.delegate = self;
    [request startSynchronous];
    
    //[self getLoginRet];
}


#pragma mark - ASIHTTPRequestDelegate
- (void)requestFinished:(ASIHTTPRequest *)request
{
    
    NSString *urlStr = [NSString stringWithFormat:@"%@",request.url];
    NSString *flagStr = @"";
    if (urlStr.length > 0)
    {
        NSArray *array = [urlStr componentsSeparatedByString:@"/"];
        flagStr = [array objectAtIndex:(array.count - 1)];
    }
    
    //NSLog(@"%@",flagStr);
    
    NSData *data = [request responseData];
    NSArray *array = [data objectFromJSONData];
    
    if(array == nil || array.count == 0)
    {
        if(mHUD == nil)
        {
            mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            [self.navigationController.view addSubview:mHUD];
            mHUD.delegate = self;
            [mHUD show:YES];
        }
        mHUD.mode =MBProgressHUDModeText;
        mHUD.labelText = @"登录失败";
        [mHUD hide:YES afterDelay:1.5];
        return;
    }
        
    NSString *item0 = [array objectAtIndex:0];
    if(![item0 isEqualToString:kResponseOk])
    {
        if(mHUD == nil)
        {
            mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            [self.navigationController.view addSubview:mHUD];
            mHUD.delegate = self;
            [mHUD show:YES];
        }
        mHUD.mode =MBProgressHUDModeText;
        mHUD.labelText = @"登录失败";
        [mHUD hide:YES afterDelay:1.5];
        return;
    }
    else 
    {
        if(array.count >1)
        {
            FMManager *fm = [FMManager sharedInstance];
            fm.isLogin = YES;
            fm.updateInboxCtrl = YES;
            fm.updateMsgCtrl = YES;
            fm.updateSecondCtrl = YES;
            
            NSDictionary *dic = [array objectAtIndex:1];
            
            NSString *userAccountid = [dic objectForKey:@"userAccountid"];
            if(userAccountid)
            {
                [SFHFKeychainUtils storeUsername:kUserName andPassword:userAccountid forServiceName:kAppName updateExisting:YES error:nil];
            }
            
            NSString *userid = [NSString stringWithFormat:@"%d",[[dic objectForKey:kUserid] intValue]];
            if(userid)
            {
                fm.userId = userid;
                DLog(@"fm.userId = %@",fm.userId);
                [SFHFKeychainUtils storeUsername:kUserid andPassword:userid forServiceName:kAppName updateExisting:YES error:nil];
            }
            
            NSString *photoName= [dic objectForKey:kUserPhotoName];
            if(photoName)
            {
                fm.userPhotoName = photoName;
                [SFHFKeychainUtils storeUsername:kUserPhotoName andPassword:photoName forServiceName:kAppName updateExisting:YES error:nil];
            }
            
            NSString *userType= [NSString stringWithFormat:@"%d",[[dic objectForKey:kModeIdentify] intValue]];
            if(userType)
            {
                fm.modeIdentify = userType;
                [SFHFKeychainUtils storeUsername:kModeIdentify andPassword:userType forServiceName:kAppName updateExisting:YES error:nil];
            }
        
            [SFHFKeychainUtils storeUsername:kUserName andPassword:self.name forServiceName:kAppName updateExisting:YES error:nil];
            
            [FMManager deletePersonalMessageOfLocal:userid];
            
            if(mHUD == nil)
            {
                mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
                [self.navigationController.view addSubview:mHUD];
                mHUD.delegate = self;
                [mHUD show:YES];
            }
            mHUD.mode =MBProgressHUDModeText;
            mHUD.labelText = @"登录成功";
            [mHUD hide:YES afterDelay:1];
        }
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    if (error)
    {
        if(mHUD == nil)
        {
            mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            [self.navigationController.view addSubview:mHUD];
            mHUD.delegate = self;
            [mHUD show:YES];
        }
        mHUD.mode =MBProgressHUDModeText;
        mHUD.labelText = @"网络链接失败";
        [mHUD hide:YES afterDelay:1.5];
    }
}

- (void)getLoginRet
{
    if(self.delegate)
    {
        FMManager *manager = [FMManager sharedInstance];
        manager.isLogin = YES;
        [self.delegate loginOK];
        [self dismissModalViewControllerAnimated:YES];
    }
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
	// Remove HUD from screen when the HUD was hidded
    
    if([mHUD.labelText isEqualToString:@"登录成功"])
    {
        [self dismissModalViewControllerAnimated:YES];
    }
	[mHUD removeFromSuperview];
	[mHUD release];
	mHUD = nil;
}

#pragma mark -
#pragma mark RegViewControllerDelegate methods
-(void)hadReg:(NSString *)nameStr
{
    self.nameTextField.text = nameStr;
    self.name = nameStr;
    [self.tableView reloadData];
}
@end
